from django import http
from django.contrib.auth import authenticate, login, logout
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
# Create your views here.


from player.models import Score,Rank


class ShowView(View):
    """
    展示玩家分数排行
    """
    def get(self,request):
        """

        :param request: 用户名
        :return: 查询结果字典数据
        """

        players = {'scores': [{'ranking': scor.rank.rank, 'client': scor.client, 'score': scor.score} for scor in
                              Score.objects.all().order_by('-score')]}

        count = Score.objects.all().count()
        uscore = Score.objects.filter(client=request.user).first()
        uscore = {'ranking': uscore.rank.rank, 'score': uscore.score,'name':uscore.client}
        # 构建返回数据
        return render(request, 'show.html', {'players':players,'count':count,'uscore':uscore})


    def post(self,request):
        """
        按条件查询
        :param request:
        :return:
        """
        try:
            start = int(request.POST.get('start'))
            end = int(request.POST.get('end'))
        except ValueError as e1:
            return http.JsonResponse({'status': 'error'})
        context = {'scores': [{'ranking': scor.rank.rank, 'client': scor.client, 'score': scor.score} for scor in
                              Score.objects.all().order_by('-score')[start - 1:end]]}
        uscore = Score.objects.filter(client=request.user).first()
        uscore = {'ranking': uscore.rank.rank, 'score': uscore.score, 'name': uscore.client}
        return render(request, 'show.html',{'players':context,'uscore':uscore})


class UploadView(View):
    """
    上传分数
    """
    def get(self,request):

        return render(request,'upload.html')

    def post(self,request):
        # 接受页面上传的数据
        score = request.POST.get('score', '')
        if score:
            # 获取数据库的数据
            old_scor = Score.objects.filter(client=request.user).first()
            if old_scor:
                if old_scor.score != score:
                    old_scor.score = score
                    old_scor.save()
            else:
                Score.objects.create(client=request.user, score=score)
            # 排名表数据更新
            Rank.objects.all().delete()
            score_li = [score_obj.id for score_obj in Score.objects.all().order_by('-score')]
            n = 1
            for i in score_li:
                Rank.objects.create(c_id_id=i, rank=n)
                n = n + 1
            return JsonResponse({'status': 'sucess'})
        return JsonResponse({'status': 'error'})


class Logout(View):

    def get(self,request):
        logout(request)
        return render(request,'login.html')


class LoginView(View):
    """
    用户登陆
    """
    def get(self, request):
        """
        请求登陆页面
        :param request: 请求
        :return: 登陆页面
        """

        return render(request, 'login.html')

    def post(self, request):
        """
        登录
        :param request:
        :return: 响应上传页面
        """

        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        # 根据获取的用户名密码去数据库查询，并返回user对象
        user = authenticate(request,username=username, password=password)
        # user = User.objects.get(username=username)
        if user:
            login(request, user,backend='django.contrib.auth.backends.ModelBackend')

            response = redirect(reverse('play:upload'))
            response.set_cookie('username',user.username, max_age=3600*24*15)
        else:
            return redirect(reverse('play:login'))
        return response


